<template>
  <el-aside :width="isCollapse ? '64px' : '200px'">
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <template v-if="!permissionStore.hasGenerated">
        <div class="loading-container">
          <span class="loading-text">路由加载中...</span>
        </div>
      </template>
      <el-menu
        v-else
        :default-active="activeMenu"
        background-color="#001529"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        :collapse="isCollapse"
        :collapse-transition="false"
        router
      >
        <template v-for="route in processedRoutes" :key="route.path">
          <!-- 处理嵌套路由 -->
          <el-submenu 
            v-if="route.children?.length"
            :index="cleanPath(route.path)"
          >
            <template #title>
              <span>{{ route.meta?.title || route.name }}</span>
            </template>
            <el-menu-item
              v-for="child in route.children"
              :key="child.path"
              :index="cleanPath(child.path)"
            >
              {{ child.meta?.title || child.name }}
            </el-menu-item>
          </el-submenu>

          <!-- 单一路由项 -->
          <el-menu-item
            v-else
            :index="cleanPath(route.path)"
          >
            <span>{{ route.meta?.title || route.name }}</span>
          </el-menu-item>
        </template>
      </el-menu>
    </el-scrollbar>
  </el-aside>
</template>

<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { usePermissionStore } from '@/stores/permission'

const route = useRoute()
const permissionStore = usePermissionStore()

// 路径格式化方法
const cleanPath = (path) => {
  return path?.replace(/^\/+/, '') || ''
}

// 处理后的路由数据
const processedRoutes = computed(() => {
  const filterRoutes = (routes) => 
    routes
      .filter(route => {
        const hasValidComponent = !!route.component
        const hasVisibleChildren = route.children?.some(child => !child.meta?.hidden)
        return !route.meta?.hidden && (hasValidComponent || hasVisibleChildren)
      })
      .map(route => ({
        ...route,
        path: cleanPath(route.path),
        children: route.children ? filterRoutes(route.children) : []
      }))
  
  return filterRoutes(permissionStore.routes)
})

// 当前激活菜单
const activeMenu = computed(() => {
  return route.meta.activeMenu || cleanPath(route.path)
})

// 接收折叠状态
const props = defineProps({
  isCollapse: {
    type: Boolean,
    default: false
  }
})
</script>

<style lang="scss" scoped>
.el-aside {
  transition: width 0.3s ease;
  background-color: #001529;
  
  .el-menu {
    border-right: none;
    &:not(.el-menu--collapse) {
      width: 200px;
    }
  }
}

.loading-container {
  padding: 20px;
  text-align: center;
  
  .loading-text {
    color: #fff;
    font-size: 14px;
  }
}
</style>